package com.sikaryofficial.backend.controller.information;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.sikaryofficial.backend.annotation.TenantFilter;
import com.sikaryofficial.backend.config.TenantFilterProperties;
import com.sikaryofficial.backend.constant.ArticleLabelEnum;
import com.sikaryofficial.backend.domain.dto.SysDictDataDTO;
import com.sikaryofficial.backend.domain.dto.req.content.ContentDeleteReq;
import com.sikaryofficial.backend.domain.dto.req.information.ArticleAuditListReq;
import com.sikaryofficial.backend.domain.dto.req.information.ArticleAuditReq;
import com.sikaryofficial.backend.domain.dto.req.information.ArticleBackendSaveReq;
import com.sikaryofficial.backend.domain.entity.Article;
import com.sikaryofficial.backend.manager.BackendContentManager;
import com.sikaryofficial.backend.manager.DataRemoveManager;
import com.sikaryofficial.backend.manager.information.ArticleFrontEndManager;
import com.sikaryofficial.backend.service.IArticleService;
import com.sikaryofficial.backend.service.article.cache.ArticleCacheService;
import com.sikaryofficial.common.core.constant.BrandEnum;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.common.core.utils.HiResultUtil;
import com.sikaryofficial.common.core.utils.PageUtil;
import com.sikaryofficial.common.core.web.controller.BaseController;
import com.sikaryofficial.common.core.web.domain.HiResult;
import com.sikaryofficial.common.core.web.domain.PageResult;
import com.sikaryofficial.common.log.annotation.Log;
import com.sikaryofficial.common.log.enums.BusinessType;
import com.sikaryofficial.common.security.annotation.RequiresPermissions;
import com.sikaryofficial.system.api.model.infomation.ArticleDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 文章审批日志Controller
 *
 * @author qinjinyuan
 * @date 2024-04-10
 */
@RestController
@RequestMapping("/article/backend")
@Api(tags = "资讯-后台管理")
@Validated
@SuppressWarnings(value = "unchecked")
public class ArticleBackendController extends BaseController {
    @Autowired
    private ArticleFrontEndManager articleManager;
    @Autowired
    private BackendContentManager contentManager;
    @Autowired
    private DataRemoveManager dataRemoveManager;
    @Autowired
    private TenantFilterProperties tenantFilterProperties;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private ArticleCacheService articleCacheService;
    /**
     * 文章标签设置
     *
     * @return
     */
    @GetMapping("/label/{articleId}/{label}")
    @Log(title = "文章标签设置", businessType = BusinessType.UPDATE)
    @ApiOperation("V3.5 文章标签设置")
    @TenantFilter
    public HiResult<Boolean> articleLabelSetting( @ApiParam(value = "文章ID") @PathVariable("articleId") Long articleId,
                                            @ApiParam(value = "文章标签:0-其他,1-小口吸,2-大口吸,3-Event") @PathVariable("label")
                                            @Valid @Min(value = 0, message = "The label value cannot be less than 0")
                                            @Max(value = 3, message = "The label value cannot be greater than 3")
                                            Integer label) {
        return HiResultUtil.success(articleManager.articleLabelSetting(articleId, label));
    }

    /**
     * 文章标签（目前主要是对于大小口吸）
     */
    @PostMapping("/getArticleLabel")
    @ApiOperation("V3.5 文章标签选择项")
    public R<List<SysDictDataDTO>> getArticleLabel() {
        ArticleLabelEnum[] reportTypeEnums = ArticleLabelEnum.values();
        List<SysDictDataDTO> result = new ArrayList<>();
        for (ArticleLabelEnum reportTypeEnum : reportTypeEnums) {
            SysDictDataDTO sysDictDataDTO = new SysDictDataDTO();
            result.add(sysDictDataDTO);
            sysDictDataDTO.setDictDesc(reportTypeEnum.getName());
            sysDictDataDTO.setDictValue(reportTypeEnum.getCode() + "");
            sysDictDataDTO.setDictType("article_label");
        }
        return R.ok(result);
    }


    /**
     * 查询文章审核列表
     * <p>
     * 条件：
     * 1、发布区域 ： addressId
     * 2、品牌
     * 3、内容类型：动态、长文
     * 4、标题    （模糊检索，左匹配）
     * 5、发布人 （模糊检索，左匹配）
     * 6、创建开始时间和创建结束时间
     */
    @PostMapping("/audit/list")
    @ApiOperation("文章审核列表")
    public PageResult<ArticleDTO> auditList(@Validated @RequestBody ArticleAuditListReq req) {
        IPage<ArticleDTO> page = articleManager.auditList(req);
        return PageUtil.success(page.getRecords(), page.getTotal());
    }

    /**
     * 文章置顶设置
     *
     * @return
     */
    @GetMapping("/{articleId}/{weight}")
    @Log(title = "文章置顶设置", businessType = BusinessType.UPDATE)
    @ApiOperation("文章置顶设置")
    @Validated
    @TenantFilter
    public HiResult<Boolean> saveWeight(@ApiParam(value = "文章ID") @PathVariable("articleId") Long articleId,
                                        @ApiParam(value = "权重 ：整数，值越大，排序越靠前") @PathVariable("weight")
                                        @Min(value = 0, message = "The weight value cannot be less than 0")
                                        Integer weight) {
        return HiResultUtil.success(articleManager.saveWeight(articleId, weight));
    }

    /**
     * 文章置顶设置
     *
     * @return
     */
    @GetMapping("/kol/{articleId}/{hasKol}")
    @Log(title = "文章KOL设置", businessType = BusinessType.UPDATE)
    @ApiOperation("V3.1 文章KOL设置")
    @Validated
    @TenantFilter
    public HiResult<Boolean> saveKolSetting(@ApiParam(value = "文章ID") @PathVariable("articleId") Long articleId,
                                            @ApiParam(value = "是否为kol帖子, 0-否 1-是") @PathVariable("hasKol")
                                            @Min(value = 0, message = "The kol value cannot be less than 0")
                                            @Max(value = 1, message = "The kol value cannot be greater than 1")
                                            Integer hasKol) {
        return HiResultUtil.success(articleManager.saveKolSetting(articleId, hasKol));
    }

    /**
     * 屏蔽(文章)
     */
    @PostMapping("/shieldByObjId")
    @ApiOperation("屏蔽(文章)")
    @TenantFilter
    public R<Boolean> shieldByObjId(@Validated @RequestBody ContentDeleteReq req) {
        Article article = articleService.getById(req.getObjectId());
        articleCacheService.clearOwnerCache(article.getCreatedBy());
        return R.ok(contentManager.shieldByObjId(req));
    }

    @PostMapping("/audit")
    @ApiOperation("文章审核")
    @RequiresPermissions("article:edit:short")
    @TenantFilter
    public R<Boolean> auditArticle(@Validated @RequestBody ArticleAuditReq req) {
        return R.ok(articleManager.auditArticle(req));
    }

    /**
     * 文章删除
     * 1、删除当前文章
     * 2、删除当前文章下面的 评论、回复及 相关所有用户行为数据：点赞，分享，评论
     * 3、删除当前文章的parent_id = cur_article_id
     * 4、如果有缓存的，需要进行缓存数据更新
     *
     * @param articleIds
     * @return
     */
    @Log(title = "文章", businessType = BusinessType.DELETE)
    @GetMapping("/delete/{articleIds}")
    @ApiOperation("删除文章")
    @RequiresPermissions("article:edit:short")
    @TenantFilter
    public R<Boolean> remove(@ApiParam(value = "articleIds 多个英文逗号分隔") @PathVariable String articleIds) {
        List<Long> articleIdList = Lists.newArrayList();
        Arrays.stream(articleIds.split(",")).forEach(item -> articleIdList.add(Long.parseLong(item)));
        // 删除当前文章
        articleManager.remove(articleIds);
        // 删除当前文章下面的 评论、回复及 相关所有用户行为数据：点赞，分享，评论
        dataRemoveManager.deleteArticleByObjId(articleIdList);
        return R.ok(true);
    }

    @Log(title = "后台新增或保存文章", businessType = BusinessType.INSERT)
    @PostMapping(value = "/save")
    @ApiOperation("后台新增或保存文章")
    @RequiresPermissions({"article:edit:long", "article:edit:short"})
    public R<Long> saveArticle(@Validated @RequestBody ArticleBackendSaveReq req) {
        if (CharSequenceUtil.isBlank(req.getArticleSite())) {
            req.setArticleSite(BrandEnum.HISMK.getCode());
        }
        // 设置文章的发布品牌
        Integer tenantId = tenantFilterProperties.getTenantByBrand(req.getBrandNo());
        req.setTenantId(Objects.isNull(tenantId) ? BrandEnum.HISMK.getValue() : tenantId);
        return R.ok(articleManager.saveBackendArticle(req));
    }
}
